﻿using Android.Bluetooth;
using Java.IO;
using Java.Util;
using nhCore;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using File = System.IO.File;

namespace WSYmi.MainAct
{
    internal class FileData
    {
        static string TAG { get; } = typeof(FileData).FullName;

        /// <summary>
        /// 互斥体，等待文件访问
        /// </summary>
        private static System.Threading.AutoResetEvent AreFileWait = new System.Threading.AutoResetEvent(true);


        /// <summary>
        /// 取应用文件夹下的所有.csv文件
        /// </summary>
        /// <returns>所有csv文件List</returns>
        public static List<CsvFileInfo> GetFileInfos()
        {
            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            List<CsvFileInfo> fileInfos = new List<CsvFileInfo>();
            foreach (var pathFileName in Directory.EnumerateFiles(path, "*.csv"))
            {
                string fileName = Path.GetFileNameWithoutExtension(pathFileName);//没有路径和后缀
                var names = fileName.Split(',');//

                CsvFileInfo fileInfo = new CsvFileInfo()
                {
                    Name = Util.GetArrayElements<string>(names, 0),
                    DeviceSn = Util.GetArrayElements<string>(names, 1),
                    Time = Util.GetArrayElements<string>(names, 2),
                    FileName = Path.GetFileName(pathFileName),
                };

                fileInfos.Add(fileInfo);
            }

            return fileInfos.OrderByDescending(f => f.Time).ToList();//最近的显示在最前面
        }

        /// <summary>
        /// 在存储库文件夹保存文本文件，并输入标题。
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="text">内容</param>
        /// <returns></returns>
        public static async void CreateTextAsync(string fileName, string text)
        {
            var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName);
            AreFileWait.WaitOne();
            using (var writer = File.CreateText(backingFile))
            {
                await writer.WriteLineAsync(text);
                writer.Close();
            };
            AreFileWait.Set();
        }

        /// <summary>
        /// 加text到存储库文件夹文本文件的尾部
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="text">内容</param>
        /// <returns></returns>
        public static async void AppendTextAsync(string fileName, string text)
        {
            AreFileWait.WaitOne();
            var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName);
            await File.AppendAllTextAsync(backingFile, text + "\r\n");
            AreFileWait.Set();
        }

        /// <summary>
        /// 从存储库文件夹读出文本文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>返回内容，一行一个string</returns>
        public static async Task<List<string>> ReadTextAsync(string fileName)
        {
            var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName);

            if (backingFile == null || !File.Exists(backingFile))
            {
                return null;
            }

            List<string> ret = new List<string>();
            AreFileWait.WaitOne();
            using (var reader = new StreamReader(backingFile, true))
            {
                string line;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    ret.Add(line);
                }
                reader.Close();
            }
            AreFileWait.Set();

            return ret;
        }
    }
}